import { login, getUserInfo } from '@/api/user'
import {
  getToken,
  setToken,
  setCookie,
  removeToken} from '@/utils/cookie'

const user = {
  state: {
    token: getToken(),
    username: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.username = name
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      const username = encodeURIComponent(userInfo.username.trim())
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          console.log(response)
          const data = response
          setToken(data.token)
          // 防止刷新页面username丢失
          setCookie('username', username)
          commit('SET_NAME', username)
          commit('SET_TOKEN', data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户菜单信息
    getInfo ({ commit }, username) {
      return new Promise((resolve, reject) => {
        getUserInfo(username).then(response => {
          const data = response
          localStorage.setItem('menus', JSON.stringify(data))
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        removeToken()
        localStorage.clear()
        resolve()
      })
    }
  }
}

export default user
